import 'dart:async';
import 'dart:io';
import 'package:dokit/widget/dash_decoration.dart';
import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_confirm_cancel_dialog/common_confirm_cancel_dialog.dart';
import 'package:e_reception_flutter/net/net_api.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/mixin/user_stream_mixin.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/app_main.dart';
import 'package:e_reception_flutter/ui/index_nav/index_nav_page.dart';
import 'package:e_reception_flutter/ui/smart_home/event/refresh_smart_home_index_event.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_store_details_page.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_index_response_bean.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_one_details_page.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_store_and_terminal_page.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_store_detail_view_model.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_upload_page.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_upload_service.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_using_terminal_page.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_view_model.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/vg_global_func.dart';
import 'package:e_reception_flutter/vg_widgets/light_annotated_region_style.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:e_reception_flutter/vg_widgets/vg_mixin/navigator_page_mixin.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/mixin/vg_place_holder_status_mixin.dart';
import 'package:e_reception_flutter/vg_widgets/vg_pull_to_refresh_widget/vg_pull_to_refresh_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:matisse_android_plugin/export_matisse.dart';
import 'package:path_provider/path_provider.dart';
import 'package:photo_preview/photo_preview_export.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_permission_lib.dart';
import 'package:vg_base/vg_pull_to_refresh_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'package:video_thumbnail/video_thumbnail.dart';
import 'create_smart_home_page.dart';
import 'index_nav_page/smart_home_index_nav_page.dart';
import 'smart_home_info_page.dart';

/// 智能家居首页
class SmartHomeStoreListPage extends StatefulWidget {
  ///路由名称
  static const String ROUTER = "SmartHomeStoreListPage";
  final bool showBack;

  const SmartHomeStoreListPage({Key key, this.showBack}) : super(key: key);

  @override
  SmartHomeStoreListPageState createState() => SmartHomeStoreListPageState();

  ///跳转方法
  static Future<dynamic> navigatorPush(BuildContext context, {bool showBack}) {
    return RouterUtils.routeForFutureResult(
      context,
      SmartHomeStoreListPage(showBack: showBack,),
      routeName: SmartHomeStoreListPage.ROUTER,
    );
  }
}

class SmartHomeStoreListPageState
    extends BasePagerState<SmartHomeIndexListItemBean, SmartHomeStoreListPage>
    with
        AutomaticKeepAliveClientMixin,
        VgPlaceHolderStatusMixin,
        NavigatorPageMixin,
        UserStreamMixin{

  SmartHomeViewModel _viewModel;
  SmartHomeStoreDetailViewModel _detailViewModel;
  StreamSubscription _indexUpdateStreamSubscription;


  ///获取state
  static SmartHomeStoreListPageState of(BuildContext context) {
    final SmartHomeStoreListPageState result =
    context.findAncestorStateOfType<SmartHomeStoreListPageState>();
    return result;
  }

  @override
  void initState() {
    super.initState();
    _viewModel = new SmartHomeViewModel(this);
    _detailViewModel = new SmartHomeStoreDetailViewModel(this);
    _viewModel?.refresh();
    _indexUpdateStreamSubscription =
        VgEventBus.global.on<RefreshSmartHomeIndexEvent>()?.listen((event) {
          _viewModel?.refresh();
        });

    addUserStreamListen((value) {
      Future.delayed(Duration(milliseconds: 50), (){
        print("收到用户信息变化的回调");
        _viewModel?.refresh();
      });
    });
  }

  @override
  void dispose() {
    super.dispose();
    _indexUpdateStreamSubscription?.cancel();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return WillPopScope(
      onWillPop: ()async{
        return true;
        // if(StateHelper.has<IndexNavPage>()){
        //   return true;
        // }else{
        //   VgEventBus.global.send(new ChangeMainPageEvent(IndexNavPage.ROUTER));
        //   RouterUtils.popUntil(context, AppMain.ROUTER);
        //   return true;
        // }
      },
      child: LightAnnotatedRegion(
          child: Scaffold(
            resizeToAvoidBottomInset: false,
            resizeToAvoidBottomPadding: false,
            backgroundColor: ((data?.length??0)>0)?Color(0xFFF6F7F9):Colors.white,
            body: Column(
              children: [
                _toTopBarWidget(),
                _toMainColumnWidget(),
              ],
            ),
          )
      ),
    );
  }

  Widget _toTopBarWidget(){
    return VgTopBarWidget(
      isShowBack: (widget?.showBack??true),
      title: ((widget?.showBack??true) || (data?.length??0) == 0)?"智能家居展示":"",
      backgroundColor: Color(0xFFF6F7F9),
      titleColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      rightWidget: _toRightWidget(),
    );
  }

  Widget _toRightWidget(){
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: (){
        CreateSmartHomePage.navigatorPush(context,);
      },
      child: Visibility(
        visible: (data?.length??0) !=0,
        child: Container(
          height: 44,
          width: 50,
          alignment: Alignment.centerRight,
          child: Image.asset(
            "images/icon_add_smart_home.png",
            width: 20,
          ),
        ),
      ),
    );
  }

  Widget _toMainColumnWidget() {
    return  Expanded(
      child: MixinPlaceHolderStatusWidget(
          emptyOnClick: () => _viewModel?.refresh(),
          errorOnClick: () => _viewModel.refresh(),
          emptyWidget: _defaultEmptyCustomWidget("您还未创建任何内容"),
          errorWidget: _defaultEmptyCustomWidget("网络断线 重新获取"),
          child: VgPullRefreshWidget.bind(
              state: this,
              refreshBgColor: Colors.white,
              viewModel: _viewModel, child: _toListWidget())
      ),
    );
  }

  Widget _defaultEmptyCustomWidget(String msg) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[
        Image.asset(
          "images/icon_empty_white.png",
          width: 120,
          gaplessPlayback: true,
        ),
        SizedBox(
          height: 8,
        ),
        Text(
          msg??"您还未创建任何内容",
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
          style: TextStyle(
            color: VgColors.INPUT_BG_COLOR,
            fontSize: 13,
          ),
        ),
        SizedBox(
          height: 20,
        ),
        GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: (){
            CreateSmartHomePage.navigatorPush(context,);
          },
          child: Container(
            height: 40,
            width: 160,
            alignment: Alignment.center,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(20),
              color: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
            ),
            child: Text(
              "创建品牌或门店",
              style: TextStyle(
                  fontSize: 15,
                  color: Colors.white
              ),
            ),
          ),
        ),
      ],
    );
  }



  //品牌/门店列表
  Widget _toListWidget(){
    return SingleChildScrollView(
      child: ListView.separated(
          itemCount: data?.length??0,
          padding: EdgeInsets.only(bottom: getNavHeightDistance(context)+60, top: 0, left: 0, right: 0),
          keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
          shrinkWrap: true,
          physics: BouncingScrollPhysics(),
          itemBuilder: (BuildContext context, int index) {
            return _toItemWidget(context, index, data[index]);
          },
          separatorBuilder: (BuildContext context, int index) {
            return Container(
              height: 10,
              color: Color(0xFFF6F7F9),
            );
          }),
    );
  }

  Widget _toItemWidget(BuildContext context, int index, SmartHomeIndexListItemBean itemBean){
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: (){
        // SmartHomeOneDetailsPage.navigatorPush(context, itemBean?.shid, itemBean?.brand, itemBean?.name, itemBean?.logo);
        SmartHomeStoreDetailsPage.navigatorPush(context, itemBean?.shid, itemBean?.brand, itemBean?.name, itemBean?.logo);
      },
      child: Container(
        alignment: Alignment.centerLeft,
        padding: EdgeInsets.only(left: 15, top: 12,),
        color: Colors.white,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              padding: EdgeInsets.only(right: 15),
              child: Text(
               itemBean?.getTitle(),
                style: TextStyle(
                    fontSize: 15,
                    color: ThemeRepository.getInstance().getCardBgColor_21263C(),
                    fontWeight: FontWeight.w600
                ),
              ),
            ),
            SizedBox(height: 12,),
            Container(
              width: ScreenUtils.screenW(context) - 30,
              child: _toImageWidget(itemBean?.shid, index, itemBean?.picList),
            ),
            SizedBox(height: 6,),
            _toBottomInfoWidget(itemBean),
            SizedBox(height: 15,),
          ],
        ),
      ),
    );
  }

  ///item底部信息布局
  Widget _toBottomInfoWidget(SmartHomeIndexListItemBean itemBean){
    bool hasTer = ((itemBean.terCnt??0)>0);
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: (){
        // SmartHomeUsingTerminalPage.navigatorPush(context, itemBean);
        SmartHomeStoreAndTerminalPage.navigatorPush(context, itemBean?.shid);
      },
      child: Container(
        height: 44,
        padding: EdgeInsets.symmetric(horizontal: 12),
        margin: EdgeInsets.only(right: 15),
        alignment: Alignment.centerLeft,
        decoration: BoxDecoration(
          color: hasTer?Color(0XFF00C6C4).withOpacity(0.1):Color(0XFFF95355).withOpacity(0.1),
          borderRadius: BorderRadius.circular(4),
        ),
        child: Row(
          children: [
              Image.asset(
                hasTer?"images/icon_store_has_terminal.png":"images/icon_store_has_not_terminal.png",
                width: 15,
                height: 16,
              ),
            SizedBox(width: 7,),
            Expanded(
              child: Text(
                itemBean?.getTerInfo(),
                style: TextStyle(
                  fontSize:13,
                  color: hasTer?ThemeRepository.getInstance().getCardBgColor_21263C():Color(0XFFF95355),
                ),
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
              ),
            ),
            Image.asset(
              "images/icon_arrow_right_grey.png",
              width: 6,
            ),
          ],
        ),
      ),
    );
    // return Container(
    //   height: 40,
    //   child: Row(
    //     mainAxisAlignment: MainAxisAlignment.start,
    //     children: [
    //       Text(
    //         itemBean?.getImageInfo(),
    //         style: TextStyle(
    //           fontSize: 11,
    //           color: Color(0xFF8B93A5),
    //         ),
    //       ),
    //       Text(
    //         itemBean?.getTerInfo(),
    //         style: TextStyle(
    //           fontSize: 11,
    //           color: ((itemBean?.terCnt??0)>0)?Color(0xFF8B93A5):Color(0xFFF95355),
    //         ),
    //       ),
    //       Spacer(),
    //       GestureDetector(
    //         behavior: HitTestBehavior.opaque,
    //         onTap: (){
    //           SmartHomeInfoPage.navigatorPush(context, itemBean?.shid, SmartHomeStoreListPage.ROUTER);
    //         },
    //         child: Container(
    //           padding: EdgeInsets.symmetric(horizontal: 15),
    //           alignment: Alignment.centerLeft,
    //           height: 40,
    //           child: Text(
    //             "编辑",
    //             style: TextStyle(
    //               fontSize: 11,
    //               color: Color(0xFF8B93A5),
    //             ),
    //           ),
    //         ),
    //       ),
    //     ],
    //   ),
    // );
  }

  ///根据图片数量获取布局
  Widget _toImageWidget(String shid, int index, List<PicListBean> picList){
    int count = picList.length;
    if(count == 0){
      return _toEmptyWidget(shid);
    }
    List<PicListBean> tempList = new List();
    if(picList.length > 7){
      tempList.addAll(picList.sublist(0, 7));
    }else{
      tempList.addAll(picList);
      int extra = 7 - picList.length;
      for(int i = 0; i < extra; i++){
        tempList.add(new PicListBean());
        tempList.add(new PicListBean());
      }
    }

    return _to7ImageWidget(index, tempList);
    // if(count == 1 || count == 2 || count == 3 || count == 4 || count == 9 || count > 9){
    //   return _toGridImageWidget(count, picList);
    // }
    // if(count == 5){
    //   return _toFiveImageWidget(picList);
    // }
    // if(count == 6 || count == 7 || count ==8){
    //   return _to678ImageWidget(count, picList);
    // }
    // return _toEmptyWidget(shid);
  }

  ///6图片布局
  Widget _to7ImageWidget(int index, List<PicListBean> picList){
    //小图宽高
    double height1 = (ScreenUtils.screenW(context) - 30 - 6)/3;
    double width = height1*2 + 3;
    double height2 = 16/9 * width;
    double height3 = (height2 - 6)/3;
    double height4 = 3;
    return Container(
      width: ScreenUtils.screenW(context) - 30,
      height: height1 + height2 + height4,
      child: Column(
        children: [
          Row(
            children: [
              Container(
                  height: height2,
                  width: width,
                  child: _toImageSetLinkWidget(
                      Radius.circular(4),
                      Radius.zero,
                      Radius.zero,
                      Radius.zero,
                      picList[0],
                    needHighQuality: true,
                  )
              ),
              SizedBox(width: 3,),
              Column(
                children: [
                  Container(
                      height: height3,
                      width: height1,
                      child: _toImageSetLinkWidget(
                          Radius.zero,
                          Radius.circular(4),
                          Radius.zero,
                          Radius.zero,
                          picList[1],
                      )
                  ),
                  SizedBox(height: 3,),
                  Container(
                      height: height3,
                      width: height1,
                      child: _toImageSetLinkWidget(
                          Radius.zero,
                          Radius.zero,
                          Radius.zero,
                          Radius.zero,
                          picList[2],
                      )
                  ),
                  SizedBox(height: 3,),
                  Container(
                      height: height3,
                      width: height1,
                      child: _toImageSetLinkWidget(
                          Radius.zero,
                          Radius.zero,
                          Radius.zero,
                          Radius.zero,
                          picList[3],
                      )
                  ),
                ],
              ),
            ],
          ),
          SizedBox(height: 3,),
          Row(
            children: [
              Container(
                  height: height1,
                  width: height1,
                  child: _toImageSetLinkWidget(
                      Radius.zero,
                      Radius.zero,
                      Radius.circular(4),
                      Radius.zero,
                      picList[6],
                  )
              ),
              SizedBox(width: 3,),
              Container(
                  height: height1,
                  width: height1,
                  child: _toImageSetLinkWidget(
                      Radius.zero,
                      Radius.zero,
                      Radius.zero,
                      Radius.zero,
                      picList[5],
                  )
              ),
              SizedBox(width: 3,),
              Container(
                  height: height1,
                  width: height1,
                  child: _toImageSetLinkWidget(
                      Radius.zero,
                      Radius.zero,
                      Radius.zero,
                      Radius.circular(4),
                      picList[4],
                  )
              ),
            ],
          )
        ],
      ),
    );

  }

  ///无图页面
  Widget _toEmptyWidget(String shid){
    double width = ScreenUtils.screenW(context) - 30;
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap:
      throttle(()  async {
        _selectImage(shid);
        await Future.delayed(Duration(milliseconds: 2000));
      }),
      child: Container(
        width: width,
        height: width,
        alignment: Alignment.center,
        decoration: DashedDecoration(
          color: Color(0xFFFAFAFA),
          dashedColor: Color(0xFFCFD4DB),
          borderRadius: BorderRadius.circular(4),
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Image(
              image: AssetImage("images/icon_upload_grey.png"),
              width: 20,
              height: 20,
              color: Color(0xFF8B93A5),
            ),
            SizedBox(height: 10,),
            Text(
              "上传文件",
              style: TextStyle(
                color: Color(0xFF8B93A5),
                fontSize: 15,
              ),
            ),
          ],
        ),
      ),
    );
  }


  /// 函数节流
  ///
  /// [func]: 要执行的方法
  Function throttle(
      Future Function() func,
      ) {
    if (func == null) {
      return func;
    }
    bool enable = true;
    Function target = () {
      if (enable == true) {
        enable = false;
        func().then((_) {
          enable = true;
        });
      }
    };
    return target;
  }

  void _selectImage(String shid) async {
    List<String> resultList = await MatisseUtil.selectAll(
        context: context,
        isCanMixSelect: false,
        maxImageSize: 15,
        maxVideoSize: 1,
        videoMemoryLimit: 500*1024,
        videoDurationLimit: 10*60,
        videoDurationMinLimit: 10,
        maxAutoFinish: false,
        onRequestPermission: (msg)async{
          bool result =
          await CommonConfirmCancelDialog.navigatorPushDialog(context,
            title: "提示",
            content: msg,
            cancelText: "取消",
            confirmText: "去授权",
            confirmBgColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
            cancelBgColor: Color(0xFFF6F7F9),
            titleColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
            contentColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
            widgetBgColor: Colors.white,
          );
          if (result ?? false) {
            PermissionUtil.openAppSettings();
          }
        }
    );
    if (resultList == null || resultList.isEmpty) {
      return;
    }
    List<SmartHomeUploadItemBean> _uploadList = List();
    Map<String, ImageInfo> _imageInfoMap = new Map();
    //获取选择的图片或者视频
    String localUrl = resultList[0];
    if (StringUtils.isEmpty(localUrl)) {
      return;
    }
    if(resultList.length == 1 && MatisseUtil.isVideo(localUrl)){
      //处理视频逻辑
      loading(true, msg: "视频处理中");
      handleVideo(localUrl, _uploadList, shid);
    }else {
      loading(true, msg: "图片处理中");
      int computeCount = 0;
      resultList.forEach((element) {
        FileImage image = FileImage(File(element));
        image.resolve(new ImageConfiguration())
            .addListener(new ImageStreamListener((ImageInfo info, bool _) async{
          _imageInfoMap[element] = info;
          computeCount++;
          if(computeCount == resultList.length){
            loading(false);
            resultList.forEach((element) {
              _uploadList.add(SmartHomeUploadItemBean(
                localUrl: element,
                type: "01",
                folderWidth: _imageInfoMap[element].image.width,
                folderHeight: _imageInfoMap[element].image.height,));
            });
            _toUploadPage(_uploadList, shid);
          }
        }));
      });
    }
  }

  ///处理视频的逻辑
  void handleVideo(String localUrl, List<SmartHomeUploadItemBean> _uploadList, String shid)async{
    //视频
    SmartHomeUploadItemBean item = SmartHomeUploadItemBean(
      localUrl: localUrl, type: "02",);
    File file = File(item.localUrl);
    Directory rootPath = await getTemporaryDirectory();
    Directory tempDirectory = new Directory('${rootPath.path}/imageTemp');
    if (!tempDirectory.existsSync()) {
      tempDirectory.createSync();
    }

    String tmpVideoCover = await VideoThumbnail.thumbnailFile(
      video: item.localUrl,
      thumbnailPath: tempDirectory?.path,
      imageFormat: ImageFormat.JPEG,
      maxWidth: 1920,
      quality: 100,
    );
    item.videoLocalCover = tmpVideoCover;
    item.videoLocalCover = tmpVideoCover;
    //
    VideoPlayerController videoController = VideoPlayerController.file(file);
    await videoController.initialize();
    item.videoDuration = videoController?.value?.duration?.inSeconds;
    item.folderWidth = videoController?.value?.size?.width?.floor();
    item.folderHeight = videoController?.value?.size?.height?.floor();
    item.folderStorage = file.lengthSync();
    _uploadList.add(item);
    videoController.dispose();
    loading(false);
    _toUploadPage(_uploadList, shid);
  }

  ///跳转到上传页面
  _toUploadPage(List<SmartHomeUploadItemBean> uploadList, String shid)async{
    String cacheKey = NetApi.GET_CATEGORY_LIST + (UserRepository.getInstance().getCacheKeySuffix()?? "")
        + shid;
    _detailViewModel.getCategoryOnLine(shid, cacheKey, null, onGetCategory: (value)async{
      String router = SmartHomeStoreListPage.ROUTER;
      if(!StateHelper.has<IndexNavPage>()){
        router = AppMain.ROUTER;
      }
      bool result = await SmartHomeUploadPage.navigatorPush(context, uploadList[0], uploadList,shid, value, router: router);
    });
  }

  ///1 2 3 4 9网格图片布局
  Widget _toGridImageWidget(int count, List<PicListBean> picList){
    return Stack(
      children: [
        GridView.builder(
          padding: EdgeInsets.all(0),
          itemCount: count>9?9:count,
          physics: BouncingScrollPhysics(),
          shrinkWrap: true,
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: getCrossCount(count),
            mainAxisSpacing: 3,
            crossAxisSpacing: 3,
            childAspectRatio: 1 / 1,
          ),
          itemBuilder: (BuildContext context, int index) {
            return _toImageSetLinkWidget(
                getTopLeftRadius(index),
                getTopRightRadius(count, index),
                getBottomLeftRadius(count, index),
                getBottomRightRadius(count, index),
                picList[index],
            );
          },
        ),
        Positioned(
          right: 0,
          bottom: 0,
          child: Visibility(
            // visible: (count??0)>9,
            visible: false,
            child: Container(
              alignment: Alignment.center,
              height: 18,
              constraints: BoxConstraints(minWidth: 28, maxWidth: 36),
              margin: const EdgeInsets.only(bottom: 4, right: 4),
              decoration: BoxDecoration(
                color: Color(0xFF000000).withOpacity(0.7),
                borderRadius: BorderRadius.circular(9),
              ),
              child: Text(
                ((count??0)>99)?"99图":"${count??0}图",
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                    color: Colors.white,
                    fontSize: 10,
                    height: 1.2
                ),
              ),
            ),
          ),
        ),
      ],
    );
  }

  //获取左上圆角
  Radius getTopLeftRadius(int index){
    if(index == 0){
      return Radius.circular(4);
    }else{
      return Radius.zero;
    }
  }

  //获取右上圆角
  Radius getTopRightRadius(int count, int index){
    if(count == 1){
      return Radius.circular(4);
    }
    if(count == 2 || count == 3){
      if(index == (count - 1)){
        return Radius.circular(4);
      }else{
        return Radius.zero;
      }
    }
    //9是第三个
    if(count >= 9){
      if(index == 2){
        return Radius.circular(4);
      }else{
        return Radius.zero;
      }
    }
    //4 5 6 7 8 的都是第二个
    if(index == 1){
      return Radius.circular(4);
    }else{
      return Radius.zero;
    }
  }

  //获取左下圆角
  Radius getBottomLeftRadius(int count, int index){
    if(count == 1 || count == 2 || count == 3){
      if(index == 0){
        return Radius.circular(4);
      }else{
        return Radius.zero;
      }
    }
    if(count == 4 || count == 5){
      if(index == 2){
        return Radius.circular(4);
      }else{
        return Radius.zero;
      }
    }
    if(count >= 9){
      if(index == 6){
        return Radius.circular(4);
      }else{
        return Radius.zero;
      }
    }
    if(index == 3){
      return Radius.circular(4);
    }else{
      return Radius.zero;
    }
  }

  //获取右下圆角
  Radius getBottomRightRadius(int count, int index){
    if(count <= 6){
      if(index == count-1){
        return Radius.circular(4);
      }else{
        return Radius.zero;
      }
    }
    //9是第9个
    if(count >= 9){
      if(index == 8){
        return Radius.circular(4);
      }else{
        return Radius.zero;
      }
    }
    if(index == 5){
      return Radius.circular(4);
    }else{
      return Radius.zero;
    }
  }

  int getCrossCount(int count){
    if(count == 1){
      return 1;
    }
    if(count >= 9){
      return 3;
    }
    if(count % 2 == 0){
      return 2;
    }
    if(count % 3 == 0){
      return 3;
    }
    return 3;
  }
  ///5图片布局
  Widget _toFiveImageWidget(List<PicListBean> picList){
    double height1 = (ScreenUtils.screenW(context) - 30 - 3)/2;
    double height2 = (ScreenUtils.screenW(context) - 30 - 6)/3;
    double height3 = 3;
    return Container(
      width: ScreenUtils.screenW(context) - 30,
      height: height1 + height2 + height3,
      child: Column(
        children: [
          _toTwoImageWidget(5, height1, picList),
          SizedBox(height: 3,),
          _toThreeImageWidget(5, 2, height2, picList.sublist(2)),
        ],
      ),
    );
  }
  ///6图片布局
  Widget _to678ImageWidget(int count, List<PicListBean> picList){
    //小图宽高
    double height1 = (ScreenUtils.screenW(context) - 30 - 6)/3;
    double height2 = ScreenUtils.screenW(context) - 30 - 3 - height1;
    double height3 = 3;
    return Container(
      width: ScreenUtils.screenW(context) - 30,
      height: height1 + height2 + height3,
      child: Stack(
        children: [
          Column(
            children: [
              _toOneBigTwoSmallWidget(8, height1, height2, picList),
              SizedBox(height: 3,),
              _toThreeImageWidget(8, 3, height1, picList.sublist(3)),
            ],
          ),
          Visibility(
            // visible: (count??0)>6,
            visible: false,
            child: Align(
              alignment: Alignment.bottomRight,
              child: Container(
                alignment: Alignment.center,
                height: 18,
                constraints: BoxConstraints(minWidth: 28, maxWidth: 36),
                margin: const EdgeInsets.only(bottom: 4, right: 4),
                decoration: BoxDecoration(
                  color: Color(0xFF000000).withOpacity(0.7),
                  borderRadius: BorderRadius.circular(9),
                ),
                child: Text(
                  "${count??0}图",
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                      color: Colors.white,
                      fontSize: 10,
                      height: 1.2
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );

  }
  ///不规则上部分两图布局
  Widget _toTwoImageWidget(int count, double height, List<PicListBean> picList){
    return Row(
      children: [
        Container(
            height: height,
            width: height,
            child: _toImageSetLinkWidget(
                getTopLeftRadius(0),
                getTopRightRadius(count, 0),
                getBottomLeftRadius(count, 0),
                getBottomRightRadius(count, 0),
                picList[0],
            )
        ),
        SizedBox(width: 3,),
        Container(
            height: height,
            width: height,
            child: _toImageSetLinkWidget(
                getTopLeftRadius(1),
                getTopRightRadius(count, 1),
                getBottomLeftRadius(count, 1),
                getBottomRightRadius(count, 1),
                picList[1],
            )
        ),
      ],
    );
  }
  ///不规则下部分三图
  ///startCount前面已经有几个图了
  Widget _toThreeImageWidget(int count, int startIndex, double height, List<PicListBean> picList){
    return Row(
      children: [
        Container(
            height: height,
            width: height,
            child: _toImageSetLinkWidget(
                getTopLeftRadius(startIndex+0),
                getTopRightRadius(count, startIndex+0),
                getBottomLeftRadius(count, startIndex+0),
                getBottomRightRadius(count, startIndex+0),
                picList[0],
            )
        ),
        SizedBox(width: 3,),
        Container(
            height: height,
            width: height,
            child: _toImageSetLinkWidget(
                getTopLeftRadius(startIndex+1),
                getTopRightRadius(count, startIndex+1),
                getBottomLeftRadius(count, startIndex+1),
                getBottomRightRadius(count, startIndex+1),
                picList[1],
            )
        ),
        SizedBox(width: 3,),
        Container(
            height: height,
            width: height,
            child: _toImageSetLinkWidget(
                getTopLeftRadius(startIndex+2),
                getTopRightRadius(count, startIndex+2),
                getBottomLeftRadius(count, startIndex+2),
                getBottomRightRadius(count, startIndex+2),
                picList[2],
            )
        ),
      ],
    );
  }
  ///不规则一大图。两小图
  Widget _toOneBigTwoSmallWidget(int count,double height1, double height2, List<PicListBean> picList){
    return Row(
      children: [
        Container(
            height: height2,
            width: height2,
            child: _toImageSetLinkWidget(
                getTopLeftRadius(0),
                getTopRightRadius(count, 0),
                getBottomLeftRadius(count, 0),
                getBottomRightRadius(count, 0),
                picList[0],
            )
        ),
        SizedBox(width: 3,),
        Column(
          children: [
            Container(
                height: height1,
                width: height1,
                child: _toImageSetLinkWidget(
                    getTopLeftRadius(1),
                    getTopRightRadius(count, 1),
                    getBottomLeftRadius(count, 1),
                    getBottomRightRadius(count, 1),
                    picList[1],
                )
            ),
            SizedBox(height: 3,),
            Container(
                height: height1,
                width: height1,
                child: _toImageSetLinkWidget(
                    getTopLeftRadius(2),
                    getTopRightRadius(count, 2),
                    getBottomLeftRadius(count, 2),
                    getBottomRightRadius(count, 2),
                    picList[2],
                )
            ),
          ],
        ),
      ],
    );
  }
  ///图片widget
  Widget _toImageSetLinkWidget(Radius topLeft, Radius topRight, Radius bottomLeft, Radius bottomRight,
  PicListBean imageData, {bool needHighQuality}){
    String asset = "images/icon_smart_home_video_play.png";
    if (imageData?.is3DLink() ?? false) {
      asset = "images/icon_smart_home_3d_link.png";
    }
    return ClipRRect(
      borderRadius: BorderRadius.only(topLeft: topLeft, topRight: topRight, bottomLeft: bottomLeft, bottomRight: bottomRight),
      child: Stack(
        children: [
          Container(
            constraints: BoxConstraints.expand(),
            child: VgCacheNetWorkImage(
              (imageData.getCoverUrl()??""),
              imageQualityType: (needHighQuality??false)?ImageQualityType.high:ImageQualityType.middle,
            ),
          ),
          Align(
            alignment: Alignment.center,
            child: Visibility(
              visible: (imageData?.isVideo()??false) || (imageData?.is3DLink()??false),
              child: Image.asset(
                asset,
                width: 40,
              ),
            ),
          ),
          // Visibility(
          //   visible: isExample,
          //   child: Positioned(
          //     top: 0,
          //     left: 0,
          //     child: Image.asset(
          //       "images/icon_smart_home_example.png",
          //       width: 30,
          //     ),
          //   ),
          // ),
        ],
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}